{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "code started\n",
      "key error\n",
      "finally\n"
     ]
    }
   ],
   "source": [
    "# try except finally\n",
    "\n",
    "try:\n",
    "#     f_read = open('bobby.txt')\n",
    "    print('code started')\n",
    "    raise KeyError\n",
    "except KeyError as e:\n",
    "    print('key error')\n",
    "else:\n",
    "    # 如果没有except代码被执行，就会执行else语句块\n",
    "    print('other error')\n",
    "finally:\n",
    "    # 总是会执行\n",
    "    print('finally')\n",
    "#     f_read.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "code started\n",
      "key error\n",
      "finally\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "# 函数返回栈底的4\n",
    "def exe_try():\n",
    "    try:\n",
    "        print('code started')\n",
    "        raise KeyError\n",
    "        return 1\n",
    "    except KeyError as e:\n",
    "        print('key error')\n",
    "        return 2\n",
    "    else:\n",
    "        # 如果没有except代码被执行，就会执行else语句块\n",
    "        print('other error')\n",
    "        return 3\n",
    "    finally:\n",
    "        # 总是会执行\n",
    "        print('finally')\n",
    "        return 4\n",
    "    \n",
    "if __name__ == '__main__':\n",
    "    result = exe_try()\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "enter\n",
      "doing something\n",
      "exit\n"
     ]
    }
   ],
   "source": [
    "## 上下文管理器协议 with\n",
    "## 涉及的魔法函数\n",
    "## __enter__\n",
    "## __exit__\n",
    "\n",
    "class Sample():\n",
    "    def __enter__(self):\n",
    "        print('enter')\n",
    "        # 获取资源\n",
    "        return self\n",
    "    def __exit__(self, exc_type, exc_val, exc_tb):\n",
    "        # 释放资源\n",
    "        print('exit')\n",
    "    def do_something(self):\n",
    "        print('doing something')\n",
    "\n",
    "with Sample() as sample:\n",
    "    sample.do_something()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
